﻿using Inovout.Cloud.Client.Storage.Data;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Inovout.Cloud.Client.Storage.QuickStarts
{
    class Program
    {
        static string baseUri = "http://storage.3cloud.dev";
        static string api_key;
        static string project_name;
        static void Main(string[] args)
        {

            api_key = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
            project_name = System.Configuration.ConfigurationManager.AppSettings["ProjectName"];
            Documents();
            return;
            Run(true);
            Console.Write("ok");
            Console.Read();
        }

        private static void Run(bool isComfirm = false)
        {
            string bucket_name = "js" + DateTime.Now.Ticks.ToString() + Guid.NewGuid().ToString();
            CreateBucket(api_key, project_name, bucket_name);

            string object_name = "jquery-1.1.4.min.js";
            using (var fileStream = new MemoryStream(Encoding.UTF8.GetBytes("hello hello1 " + object_name)))
            {
                CreateAndUploadObject(api_key, bucket_name, object_name, fileStream);
            }

            //var owner = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];

            //GetMembershipUsedStorageSpace(owner);

            //DownloadObject(bucket_name, object_name);


        }
        private static void Documents()
        {
            string bucket_name = "documents";
            //CreateBucket(api_key, project_name, bucket_name);

            HttpClient client = new HttpClient();
            var obj = new Data.Object
                       {
                           Name = DateTime.Now.Ticks.ToString()
                       };
            HttpResponseMessage response = null;
            string str = JsonConvert.SerializeObject(obj);
            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(str)))
            {

                HttpContent content = new StreamContent(stream);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                string url = string.Format("http://sumpowerstorage.sumapp.cn/upload/v1/b/{0}/o?uploadType=resumable", bucket_name);
                url = string.Format("http://storage.sumapp.cn/upload/v1/b/{0}/o?uploadType=resumable", bucket_name);
                var task = client.PostAsync(url, content);
                task.Wait();
                response = task.Result;
            }
            Console.WriteLine("uri:" + response.Headers.Location);
            try
            {
                using (var fileStream = new MemoryStream(Encoding.UTF8.GetBytes("hello hello1 " + obj.Name)))
                {
                    HttpContent content = new StreamContent(fileStream);
                    var task = client.PostAsync(response.Headers.Location, content);
                    task.Wait();
                    response = task.Result;
                    Console.WriteLine("code:" + task.Result.StatusCode.ToString());
                    Console.WriteLine("body" + task.Result.Content.ReadAsStringAsync().Result);
                    Console.Read();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex:" + ex.Message);
                Console.Read();
            }
        }
        private static StorageService CreateSorageService(string api_key)
        {
            return new StorageService(new Inovout.Cloud.Client.Services.BaseClientService.Initializer
  {
      ApiKey = api_key
  });

        }

        private static void CreateBucket(string api_key, string proj_name, string bucket_name)
        {
            StorageService storageService = CreateSorageService(api_key);

            storageService.Buckets.Insert(new Bucket
            {
                Name = bucket_name
            }, proj_name).Execute();
        }

        private static void CreateAndUploadObject(string app_key, string bucket_name, string object_name, Stream stream)
        {
            StorageService storageService = CreateSorageService(app_key);
            var insertObject = storageService.Objects.Insert(
                new Data.Object
                {
                    Name = object_name
                }
                , bucket_name
                , stream,
                "resumable"
                ).Upload();
        }

        private static void GetMembershipUsedStorageSpace(string org_username)
        {
            string uri = baseUri + "/manager/report/GetMembershipUsedStorageSpace?owner=" + org_username;
            var request = (HttpWebRequest)WebRequest.Create(uri);
            var response = (HttpWebResponse)request.GetResponse();
            Console.Write("   UsedSpace:" + new StreamReader(response.GetResponseStream()).ReadToEnd());
            response.Close();
            request.Abort();
        }

        private static void DownloadObject(string bucket_name, string object_name)
        {
            Process.Start("IExplore.exe", string.Format("storage.3cloud.dev/{0}/{1}", bucket_name, object_name));
        }
    }
}
